package com.tanx.cqrs.eventsourcing.snapshot;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.IOException;
import java.util.Date;

/**
 *
 */
@Data
@Document
public class MongoSnapshotImpl implements Snapshot {
    private Date createDateTime;
    private String className;
    private String content;
    @Id
    private String uuid;

    public MongoSnapshotImpl() {
    }

    public MongoSnapshotImpl(Object aggregate, Object id) {
        this.uuid = id.toString();
        this.className = aggregate.getClass().getName();
        this.createDateTime = new Date();
        this.content = (String) toSnapshotContent(aggregate, id);
    }

    @Override
    public Date getCreateDateTime() {
        return createDateTime;
    }

    @Override
    public Object toSnapshotContent(Object aggregate, Object id) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(aggregate);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object toAggregate() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(content, Class.forName(className));
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
